package org.aicfve.previze.controller;

import com.hava.web.MediaType;
import com.hava.web.rest.Entity;
import org.aicfve.previze.entity.Scene;
import org.aicfve.previze.service.SceneJPAService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.List;

/**
 * Created by zhanpeng on 2017/9/21.
 */

@RestController
@RequestMapping(value="rest/scenes")
public class SceneJPARestController {

    @Autowired
    private SceneJPAService service;

    //GET /entity : get entity all list
    // TODO:添加高级搜索分页
    @RequestMapping(method = RequestMethod.GET, produces = MediaType.JSON)
    public List<Scene> list() {
        return service.getAll();
    }

    //GET /entity/{id} : get entity.id={id} object
    @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.JSON)
    public Scene get(@PathVariable("id") Long id) {

        Scene entity = service.get(id);

        if (entity == null) {
            String message = "Object :id {" + id + "} not existed.";
            System.out.println(message);
        }

        return entity;
    }

    //POST /entity : create new entity object
    @RequestMapping(method = RequestMethod.POST, consumes = MediaType.JSON)
    public ResponseEntity create(@RequestBody Scene entity, UriComponentsBuilder uriBuilder) {
        service.create(entity);

        //按照Restful风格，返回新对象的
        HttpHeaders httpheader = new HttpHeaders();

        //通过反射获取entity的url
        String EntityURL = Entity.URL(this) + "/" + entity.getId();

        //生成Respone header显示Entity创建后的资源路径
        URI uri = uriBuilder.path(EntityURL).build().toUri();
        httpheader.setLocation(uri);
        ResponseEntity responseEntity = new ResponseEntity(httpheader, HttpStatus.CREATED);

        return responseEntity;
    }

    //PUT /entity/{id} : update entity.id={id}
    @RequestMapping(method = RequestMethod.PUT, value = "/{id}", consumes = MediaType.JSON)
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void update(@RequestBody Scene entity, @PathVariable("id") Long id) {
        entity.setId(id);
        service.update(entity);
    }

    //DELETE /entity/{id} : delete entity.id={id}
    @RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void delete(@PathVariable("id") Long id) {
        service.delete(id);
    }
}
